package com.chinda.modules.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.chinda.common.utils.R;
import com.chinda.modules.entity.GeneratorEntity;
import com.chinda.modules.qo.GeneratorQO;
import com.chinda.modules.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 自动生成测试类
 *
 * @author chinda
 * @date 2020-08-09 19:53:49
 */
@RestController
@RequestMapping("/generators")
@Api(tags = "项目示例")
public class GeneratorController {

    private final GeneratorService generatorService;

    public GeneratorController(GeneratorService generatorService) {
        this.generatorService = generatorService;
    }

    /**
     * 列表
     */
    @GetMapping
    @ApiOperation(value = "查询列表信息")
    public R list() {
        List<GeneratorEntity> generatorList = generatorService.queryAll();
        return R.ok().set(generatorList);
    }

    /**
      * 分页
      * @param qo
      * @return
      */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页信息")
    public R page(@RequestBody GeneratorQO qo) {
        return R.ok().set(generatorService.queryPage(qo));
    }

    /**
      * 获取详情
      * @return
      */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取详情")
    public R info(@PathVariable("id")  Long id) {
        GeneratorEntity generator = generatorService.getOne(id);
        return R.ok().set(generator);
    }

    @PostMapping
    @ApiOperation(value = "保存信息")
    public R save(@RequestBody @Valid GeneratorEntity generator) {
        GeneratorEntity generatorR = generatorService.save(generator);
        return R.ok().set(generatorR);
    }

    /**
      * 修改全属性
      * @param generator
      * @return
      */
    @PutMapping("/{id}")
    @ApiOperation(value = "修改全属性")
    public R modify(@PathVariable("id") Long id, @RequestBody @Valid GeneratorEntity generator) {
        generator.setId(id);
        GeneratorEntity generatorR = generatorService.save(generator);
        return R.ok().set(generatorR);
    }

    /**
     * 修改局部属性
     * @param id
     * @param generator
     * @return
     */
    @PatchMapping("/{id}")
    @ApiOperation(value = "修改局部属性")
    public R patch(@PathVariable("id") Long id, @RequestBody @Valid GeneratorEntity generator) {
        GeneratorEntity generatorDB = generatorService.getOne(id);
        BeanUtil.copyProperties(generator, generatorDB, CopyOptions.create().ignoreNullValue());
        GeneratorEntity generatorR = generatorService.save(generatorDB);
        return R.ok().set(generatorR);
    }

    /**
      * 删除数据
      * @param id
      * @return
      */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据")
    public R remove(@PathVariable("id") Long id) {
        generatorService.remove(id);
        return R.ok();
    }
}
